var reportArr = [];
htconfig = {
	Default: {
		toolTipDelay: 500,
		toolTipContinual: true
	}
};

window.onload = function() {
	websocket = null;	
	map = {
		'园区': {
			name: '园区',
			mi: function(e) {
				if (e.kind === 'onDoubleClick') {
					if (e.data._displayName) {
						//检测是否点击的为模型，如果不是，则不加载模型
						let isClickDevice= modelMap.isClickDevice(e.data._displayName);					
						if (!isClickDevice){
                            if (modelMap.isBuildingTag(e.data.getTag())){
							  loadModel(e.data._displayName, map);
							}
						}
						else{
							//添加设备视频start
							vm.addCamera(e);
							//添加设备视频end
						}
					}
				}
				// 外景设备悬浮放大start
				else if (e.kind === 'onEnter') { 
					// 外景设备悬浮放大start
					vm.hoverEquipment('园区',e,'enter');
					// 外景设备悬浮放大end
				}
				else if (e.kind === 'onLeave') {
					// 外景设备离开恢复start
					vm.hoverEquipment('园区',e,'leave');
					// 外景设备离开恢复end
				}
				// 外景设备悬浮放大end
				else if (e.kind === 'onClick') {
					// 园区展示信息设备start
					if (e.data.getTag() != undefined) {
						var dname=e.data._displayName;
						if(dname=="视频监控" || dname=="门禁设备" || dname=="对讲机" || dname=="红外对射" || dname=="高压电网" || dname=="电子围栏"){
							// vm.getdev(e.data.getTag(), dname);
							//详细展示
							vm.warningposition({'deviceId':e.data.getTag(),'deviceType':e.data._displayName},'nowarn');
						}else{
							vm.getequipment(e.data.getTag());
						}
					}
					// 园区展示信息设备end
				}
				else if (e.kind === 'doubleClickBackground') {}
			}
		},
		building: {
			mi: function(e) {
				if (e.kind === 'onDoubleClick') {
					if (e.data._displayName) {
						//判断是否第三层的 modelTag才可以。
						let newModelLevelName=modelMap.match(e.data._displayName);
						if (newModelLevelName='floor'){
							if (modelMap.isFloorTag(e.data.getTag())){
								loadModel(e.data._displayName, map);
							}							
						}
					}
				}
				else if (e.kind === 'onEnter') {
					if (e.data._tag  && modelMap.isFloorTag(e.data.getTag())) {
						let underScoreIndex=e.data._tag.indexOf('_');
						let floorLevel=e.data._tag.slice(underScoreIndex+1)*1;
						if (floorLevel<0){
							floorLevel='负'+floorLevel*(-1)+'层';
						}
						else{
							floorLevel=floorLevel+'层';
						}
						vm.tipshow('building',floorLevel);
						modelMap.curShowingFloorName=e.data._displayName;
						e.data.s({
							'shape3d.color': 'rgba(0,0,0,0.4)',
							'all.color': 'rgba(0,0,0,0.4)'
						})
					}
				}
				else  if (e.kind === 'onLeave'  && modelMap.isFloorTag(e.data.getTag())) {
					modelMap.curShowingFloorName='';
				    vm.tiphide();
					e.data.s({
						'shape3d.color': 'rgba(0,0,0,0)',
						'all.color': 'rgba(0,0,0,0)'
					});
				}
				else if (e.kind === 'onClick') { //多层模型暂时不需要事件
				}
			}
		},
		floor: {
			mi: function(e) {
				if (e.kind === 'onDoubleClick') {
					//添加设备视频start
					vm.addCamera(e);
				}
				else if (e.kind === 'onClick') {
					//高亮时点击设备显示设备详情start
					if (e.data._displayName) {
						if(e.data.getTag()!=undefined && e.data._displayName!=undefined){
							vm.warningposition({'deviceId':e.data.getTag(),'deviceType':e.data._displayName},'nowarn');
						}
					}
				}else if (e.kind === 'onEnter') { 
					// 房间设备悬浮放大start
					vm.hoverEquipment('房间',e,'enter');
					// 房间设备悬浮放大end
				}else if (e.kind === 'onLeave') {

					// 房间设备离开恢复start
					vm.hoverEquipment('房间',e,'leave');
					// 房间设备离开恢复end
				}else{
					//检测右键拖动
					//	modelMap.resetModel(e.kind);
				}
			}
		},
		isStartCollect: false,
		issockect: true,
		isGlobalScene: true, // 是否处于全景模型场景中，是为true，反之为false
		openAlarm: false,
		isMuted: false,
		imageName: 'tip.json',
		intervalArr: [],
		intervalCountArr: [],
		modelJson:null//模型json文件
	}
	var tipVoice = document.querySelectorAll("#tipVoice")[0];
	dataModel = new ht.DataModel();	
	var g3d = window.g3d = new ht.graph3d.Graph3dView(dataModel);
	var oldScene = null;

    /**
	*@功能：创建园区建筑顶部标志牌
	*@author luzhifei
	*@created 2019/09/14
	*/
    createBuildingBillBoard=function(){
		modelMap.globalBuildingTagIdList.forEach(function (item) {
			let buildBoxNode=g3d.dm().getDataByTag(item);
			if (buildBoxNode!=undefined){
               //开始创建billboard
			    if (item=='F1'){ //F1由于模型特殊性，挂了许多无用的子节点
					if (buildBoxNode.getAttaches()!=undefined){
						buildBoxNode.getAttaches().clear();
					}
				}
				
			    let buildName=modelMap.globalBuildingNameList[item];
                let bNode = new ht.Node();
				let hostPos=buildBoxNode.getPosition3d();
				bNode.p3(hostPos[0], hostPos[1]+2000, hostPos[2]);
				bNode.s({
					'shape3d': 'billboard',
					'shape3d.image':'globalBuildingBoardImage',
					'3d.movable': false,
					'2d.movable': false,
					'3d.selectable': false,
					'shape3d.image.cache': false, // 是否缓存
					'shape3d.autorotate': true, // 始终面向相机
					"shape3d.transparent": true,
					'shape3d.alwaysOnTop': false, ////---- 是否需要一直在上方
					'shape3d.vector.dynamic': false,
					'shape3d.fixSizeOnScreen': false,
				});
				//bNode.a('color', '#2ECCFA');//淡蓝色
				bNode.a('msg', buildName);
				bNode.setScale3d([1.4,1.4,1.4]);
				bNode.setHost(buildBoxNode);
				dataModel.add(bNode);			   
			}
						
		});
	}
	
   

	function initModel() {		
		dataModel2 = new ht.DataModel();
		g2d = new ht.graph3d.Graph3dView(dataModel2);

		view = g3d.getView();
		document.body.appendChild(view);
		window.addEventListener('resize3d', function(e) {
			g3d.invalidate(); //在浏览器大小改变是重新3D视图
			g2d.invalidate();
		}, false);


		/* 鹰眼开始 */
		var view2d = g2d.getView();
		view2d.className = "main2d";
		view.className = "main";
		document.body.appendChild(g2d.getView());
		g2d.setFar(1000000);		
		g2d.setEye([0, 49000, 0]); //设置视角位置
		g2d.setRotatable(false); //设置不可旋转
		//g2d.pan(200, 200, true, true); //设置偏移

		dataModel2.deserialize("scenes/园区.json");
		
		//绘制鹰眼区域的手电筒
		nEagleEyeCore = new ht.Node(); 
		nEagleEyeCore.setStyle('shape3d', 'sphere');
		
		nEagleEyeHandLightCenter = new ht.Node();		
		nEagleEyeHandLightCenter.setStyle('shape3d', 'cylinder');		
		nEagleEyeHandLightCenter.s({
			'shape3d.visible': false,
			'shape3d.top.visible': false,
			'shape3d.bottom.image': 'assets/cameraCenter.png',
			'shape3d.reverse.flip': true
		});
		nEagleEyeHandLightCenter.p3(0, 0, 5000);
		nEagleEyeHandLightCenter.setSize3d(5000, 5000, 5000);
		nEagleEyeHandLight = new ht.Node();  //手电光
		nEagleEyeHandLight.setStyle('shape3d', 'rect');
		nEagleEyeHandLight.s({
			'shape3d.visible': false,
			'shape3d.top.visible': false,
			'shape3d.bottom.color': 'rgba(24,170 , 218, 0.6)',
			'shape3d.bottom.image': 'assets/cameraView.png',
			'shape3d.transparent': true,
			'shape3d.reverse.flip': true
		});
		nEagleEyeHandLight.p3(0, 0, 0);
		nEagleEyeHandLight.setSize3d(8000,8000, 8000);

        
		nEagleEyeHandLight.setHost(nEagleEyeCore);
		nEagleEyeHandLightCenter.setHost(nEagleEyeCore);
		nEagleEyeHandLightCenter.setHost(nEagleEyeHandLight);
		
		dataModel2.add(nEagleEyeCore);
		dataModel2.add(nEagleEyeHandLightCenter);
		dataModel2.add(nEagleEyeHandLight);

		var radian = rotateAngle(g3d.getEye(), g3d.getCenter());
		nEagleEyeCore.setRotationY(radian);
		nEagleEyeCore.p3([522.0339697437194, 11121.977068084903, 15988.979279792336]);
		
		//监听g3d的旋转事件
		g3d.addInteractorListener(function(e) {
			if (elePatrolObj.operationName!='none'){
				return;
			}
			if (e.kind === 'endRotate' || e.kind === 'betweenRotate') {
				var radian = rotateAngle(g3d.getEye(), g3d.getCenter());

				g2d.setCenter([0,0,0]);
				
				let modelLevelName=modelMap.match(modelMap.curModelFileName);
					
				let topModelId=modelMap.getTopModelId(modelMap.curModelFileName);
				if (modelLevelName!='园区'){
					var data = g2d.dm().getDataByTag(topModelId);				
					nEagleEyeCore.p3(data.getPosition3d()[0], eagleObj.g2dHeight, data.getPosition3d()[2]);
				}
				else{
					nEagleEyeCore.p3(g3d.getEye()[0],eagleObj.g2dHeight,g3d.getEye()[2]);
				}
				nEagleEyeCore.setRotationY(radian);
			}
		});
		/* 鹰眼结束 */
		$(document).keydown(function(event) {
			// 恢复园区视角start
			if(event.keyCode==32){
				vm.FirstAngleView(32);
			}
			// 恢复园区视角end
			if (event.keyCode == 87 || event.keyCode == 83 || event.keyCode == 65 || event.keyCode == 68) {
				var radian = rotateAngle(g3d.getEye(), g3d.getCenter());
				nEagleEyeCore.setRotationY(radian);
				nEagleEyeCore.p3(g3d.getEye()[0], eagleObj.g2dHeight, g3d.getEye()[2]);
			}
			if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
				var radian = rotateAngle(g3d.getEye(), g3d.getCenter());
				nEagleEyeCore.setRotationY(radian);
				nEagleEyeCore.p3(g3d.getEye()[0], eagleObj.g2dHeight, g3d.getEye()[2]);
			}
		});


		/* $(document).keyup(function(event) {
			i = 0;
		}); */
		
		/**获取获取弧度
		 * @param {Object} eye1  观察点
		 * @param {Object} center1  物体的中心点
		 * @return {数值}  弧度 .由于总是莫尔纳center在0,0,0，直接使用观察点即可
		 */
		function rotateAngle(eye1, center1) {
			let xLen = eye1[0]*1;
			let zLen = eye1[2]*1;
			let angle = Math.atan2(xLen, zLen);
			return angle;
		}
	}

	


    /**
	*
	* 模拟右键双击
	*/
	initDbclick = function () {
		var lastClickTime = 0;
		var clickTimer;
		window.addEventListener('mousedown', (e) => {
			//当处于电子巡更状态的时候，不执行
			if (elePatrolObj.operationName!='none'){
			  return;		
			}
			if(e.button ==2){
				if(map.isGlobalScene) return;
				var nowTime = new Date().getTime();
				if (nowTime - lastClickTime < 400) {
						/*双击*/
						lastClickTime = 0;
						clickTimer && clearTimeout(clickTimer);
						if(vm.level3) {
							vm.closewarntrue = false;
							loadModel(vm.level2, map)
						} else if(vm.level2) {
							vm.closewarntrue = false;
							g3d.dm().clear();
							loadModel('园区', map)
						}
						
				} else {
						/*单击*/
						lastClickTime = nowTime;
						clickTimer = setTimeout(() => {
						}, 400);
				}
			}
		});
	};

	isWebsocket = function() {
		if (window.WebSocket && (typeof WebSocket != 'undefined')) {
			return true;
		}
		return false;
	}

	initWebsocket = function() {
		if (isWebsocket()) {
			websocket = new WebSocket(webSocketAddr);
		} else {
			alert("您的浏览器不支持websocket!");
		}
		websocket.onerror = function() {
			vm.$message.error('连接错误!');
		}
		websocket.onmessage = function(e) {
			//当处于电子巡更状态的时候，不执行
			if (elePatrolObj.operationName!='none'){
			  return;		
			}
			if (e.data && e.data !== 'ok') {
				var res = JSON.parse(e.data);				
                let deviceTypeIdList='';				
				res.data.forEach((el,index)=>{
					vm.getAllDeviceTypeListData.forEach((el2,index2)=>{
						if(el.status=="0"){
							if(el.deviceTypeName==el2.deviceTypeName){
								$(".vioce"+el2.deviceTypeId)[0].play();
								deviceTypeIdList+=el2.deviceTypeId+',';
							}
						}
					})
				})
				
				//刷新告警信息
				vm.getwarnlist(deviceTypeIdList);
				
				if(res.data.length==1){
					var reportArrOld = [];
					reportArrOld = res.data;
					reportArr = reportArrOld;
					vm.getReportArr = reportArr;					
				}
			}
		}
		websocket.onclose = function() {
			console.log('连接已断开');
		}
	};

    /**
	*调整视角
	*@param is3d 是否3d，如果是3d，则为true，否则为false
	*@param isLoadModel 是否正在加载模型
	*/
	fixedView = function(is3d, isLoadModel) {
		g3d.setRotatable(is3d);
		g3d.setPannable(is3d);
		g3d.setWalkable(is3d);
		g3d.setResettable(is3d);
		if (!isLoadModel) {//模型切换情况下			
			if (is3d) {//3d视图
			   g3d.setCenter([modelConfig.setting.xg3dcenter*1,modelConfig.setting.yg3dcenter*1,modelConfig.setting.zg3dcenter*1]);
			   g3d.setEye([modelConfig.setting.xview*1,modelConfig.setting.yview*1,modelConfig.setting.zview*1]);		
			} else { //2d视图
				if (map.isGlobalScene) {
					
					g3d.setEye(0, 70000, 0);
					
					g3d.setCenter(0, 0, 0);
				} else {
					
					g3d.setEye(0, 10000, 0);
					
					g3d.setCenter(0, 0, 0);
				}
			}
		}
	}


    /**
	* 初始化 ht的图像信息
	*/
	function initImageDef() {
		//建筑顶部广告牌
		ht.Default.setImage('globalBuildingBoardImage', {
			"width": 3000,
			"height": 700,
			"comps": [
			    {
					"type": "shape",
					"background": "rgb(0,0,0,0.3)",
					"borderWidth": 1,
					"borderColor": "#666",
					"borderCap": "round",
					"shadowColor": "#1ABC9C",
					"displayName": "tips",
					"rotation": 3.14159,
					"closePath": true,
					"points": [
						0.84948,
						100.73809,
						0.84948,
						3000.0893,
						3000.84933,
						3000.0893,
						3000.84933,
						100.73809,
					]
				},
				{
					"type": "text",
					"text": {
						"func": "attr@msg",
						"value": ""
					},
					'align': 'center',
					'font': buildBillBoardFont,
					"color": "rgb(255,255,255)",
					"anchorX": 0,
					"rect": [
						10.84948,
						405.73809,
						3000.84933,
						25.532
					]
				},
				{
					"type": "image",
					"name":"/assets/buildFlag.png",
                    "stretch":"centerUniform",
					"rect": [
						0,
						0,
						700,
						700
					]
				}				
			]
		});
		////////////////////////////////////////////////////////////////////
		//icon.json 不可以被注释，因为所有的model的json中都有引用这个。
		//
		ht.Default.setImage('icon.json', {
			"width": 1000,
			"height": 600,
			"comps": [
			{
			 "type": "text",
			 "text": {
				"func": "attr@msg",
				"value": "厂房大楼"
			 },
			 'align': 'center',
			 'font': 'normal 100px arial',
			 "color": roomNameClor,
			 "anchorX": 0,
			 "rect": [
				10.84948,
				330.73809,
				1000.84933,
				25.532
			 ]
			}]
		 });
		 
	}


     /**
	*功能：加载模型,之后需要设置 level2,level3, modelMap.modelLevelNo
	*@param name 模型中文名称， 譬如 A1教学用房
    *@param map  即本文件中的map
    *@param isPosition 表明是否执行定位，可取值为 position或者空值
	*@param objectTag 对象标记 --目前是设备ID
	*/
	loadModel = function(name, map, isPosition, objectTag) {
		while (publicAlarmObj.isLock){
		}		
		try{
			modelMap.modelLoadStatus='loading';
			ht.Default.xhrLoad(
				'scenes/' + name + '.json',
				function(text) {
					const json = ht.Default.parse(text);
					g3d.addToDOM();
					
					/* if (!map[name]) {
						map[name] = {};
					}
					map[name].json = json; */
					map.modelJson=json;
					if (json) {
						//记录当前的模型文件名称
			            modelMap.curModelFileName=name;
						modelMap.curModelId=modelMap.modelFileNameMappingModelId[name];
                        modelMap.curModelIdPrefix=modelMap.getModelIdPrefix(modelMap.curModelId);
						let modelLevelName=modelMap.match(modelMap.curModelFileName);
					    modelConfig.modelLevelName=modelLevelName;
								
						if (modelLevelName=='园区'){
							vm.level2="";
							vm.level3="";
						}
						else if (modelLevelName=='building'){
							vm.level2=name;
							vm.level3="";
						}
						else{//三层			
							vm.level2=modelMap.getParentModelName(name);
							vm.level3=name;
						}
						
						map.isGlobalScene=(modelLevelName=='园区');
						
						//如果以下失败，可能导致异常
						//所以需要一个定时任务纠正异常
						//加载设备，高亮，定位
						sceneIn(name, isPosition, objectTag);
						//指定设备(透明框)可以做交互 interactive
						modelMap.setObjectInteractive();
												
					} else {
						console.log('获取模型【'+name+'】错误！');
					}
					modelMap.modelLoadStatus='finished';					
				}
			)
			//设备背景色
			g3d.dm().setBackground(buildBackGroundColor);
		}
		catch(exception){
			console.log(exception.message);
		}
	}
     
    /**
	*功能:进入模型
	*@param name 模型名称
	*@param isPosition 是否定位
	*@param objectTag 对象标记 目前展示支持 设备ID
	*/
	function sceneIn(name, isPosition, objectTag) {
		if (oldScene) {
			sceneOut(oldScene);
		}

        
		//在序列化之前，先设定eye等参数，避免晃眼！
		let mId = modelMap.modelFileNameMappingModelId[name];			
			//设定模型视角
		$.ajax({
			url: '/jg-api/model/getModelInfo',
			type: 'post',
			async:true,
			data: {
				modelId: mId
			},
			success: function (res) {				
				if(res.success) {
					if(res.data && res.data[0]) {
						modelConfig.setConfig(res.data,mId);
						var data = res.data[0];	
						g3d.setCenter([0,0,0]);    							
						if (data.far){
							g3d.setFar(data.far*1);
						}
						if (data.near){
							g3d.setNear(data.near*1);
						}					
						if (mId=='JG001' && data.xg3dcenter){
							g3d.setCenter([data.xg3dcenter*1,data.yg3dcenter*1,data.zg3dcenter*1]);
						}
						
						if(data.xview && data.yview && data.zview) {
							g3d.setEye(data.xview*1, data.yview*1, data.zview*1);								
						}
                        						
					}
				}
			}
		})
		
         
		g3d.deserialize(map.modelJson);
		let modelLevelName=modelMap.match(name);		
		g3d.mi(map[modelLevelName].mi, g3d);
		
		
		//设备加载，高亮，定位等等
		if (name !== '园区') {			
			
			//加载设备，高亮设备
			let deviceLoadFlag=false;			
			$.ajax({
				url: '/jg-api/device/getAllDeviceList',
				type: 'post',
				data: {
					modelId: mId
				},
				success: function(res) {
					if (res.success) {
						deviceLoadFlag=true;						
						res.data.forEach(function(item) {
							var node = new ht.Node();
							node.s({
								'shape3d': 'scenes/' + item.deviceType + '.json',
							});
							node.s('interactive',true);
							node.p3(parseInt(item.xcode), parseInt(item.ycode), parseInt(item.zcode));
							node.setTag(item.deviceId);
							node.setDisplayName(item.deviceType);
							node.setRotation3d(item.xangle*1,item.yangle*1,item.zangle*1);
							g3d.dm().add(node);
						})
						//设备高亮
						modelHighLight.setModelHighLight();	
						////显示告警标记-无论是否有定位						
						if ( modelLevelName=='floor' ||  modelLevelName=='building'){
							publicAlarmObj.createAlarmFlags(null);
						}
						
						//定位：只有楼层才可以
						if ( modelLevelName=='floor' && isPosition) {
							if (objectTag) {
								publicAlarmObj.positionDevice(objectTag,publicAlarmObj.isWarnning,null,null);
							}
						}
							
					}
				}
			})
			
				
		} 
		else {// 全景模型
		    //全景模型需要顶部增加标题            
			createBuildingBillBoard();
			$.ajax({
				url: '/jg-api/device/getDeviceList',
				type: 'post',
				data: {
					modelId: mId,
					deviceType: null,
					pageNo: 1,
					pageSize: 99999
				},
				success: function(res) {
					if (res.success) {
						res.data.forEach(function(item) {
							var node = new ht.Node();
							node.s({
								'shape3d': 'scenes/' + item.deviceType + '.json',
							});
							node.s('interactive',true);
							node.p3(parseInt(item.xcode), parseInt(item.ycode), parseInt(item.zcode));
							node.setTag(item.deviceId);
							node.setDisplayName(item.deviceType);
							node.setRotation3d(item.xangle*1,item.yangle*1,item.zangle*1);
							g3d.dm().add(node);
						})
						
						//设备高亮
						modelHighLight.setModelHighLight();	
						
						//显示告警标记-无论是否有定位
						////显示告警标记-无论是否有定位												
						publicAlarmObj.createAlarmFlags(modelConfig.globalNoPostionWarnningFlagScaleArr);						
						//定位						
						if ( isPosition && objectTag) {
							publicAlarmObj.positionDevice(objectTag,publicAlarmObj.isWarnning,null,null);
						}
						
					}
				}
			})
			
			var mapInteractor = new ht.graph3d.MapInteractor(g3d);
			g3d.setInteractors([ mapInteractor ]);
			mapInteractor.maxPhi = Math.PI * 2 / 5;
		}

		//重置鹰眼球的位置
		let topModelId=modelMap.getTopModelId(modelMap.curModelFileName);
		if (modelLevelName!='园区'){
			var data = g2d.dm().getDataByTag(topModelId);	
            if (data){			
			  nEagleEyeCore.p3(data.getPosition3d()[0], eagleObj.g2dHeight, data.getPosition3d()[2]);
			}
		}

		if(g3d.dm().getDataByTag('skybox')) {
			g3d.setSkyBox(g3d.dm().getDataByTag('skybox'));
		}
		fixedView(vm.is3dView,true);
		//g3d.dm().addScheduleTask(intervalTask);
		oldScene = name
		
	}


    
    /**
	*功能:退出模型的特定层次，并重置园区的观察点和g3d的中心点
	*@params  oldScene  老场景信息
	*/
	function sceneOut(oldscene) {
		for (key in map) {
			if (key=='园区' || key=='building' || key=='floor') {
				g3d.umi(map[key].mi, g3d);
			}
		}
		//g3d.setSkyBox(null);
		g3d.dm().clear();
	}

    /**
	*初始化
	*/
	function init() {
		initDbclick();
		initImageDef();
		// initWebsocket();
		modelConfig.oldInteractors=g3d.getInteractors();
		loadModel(map['园区'].name, map);
		initModel();
		initWebsocketMon();//打开海康视频告警
		//启动定时任务
		intervalTask=setInterval(globalTask, 500);
	}
	init();
}